package jeesample.service.impl;

import java.sql.SQLException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

import jeesample.dao.OrmLiteManager;
import jeesample.model.Room;
import jeesample.service.RoomLocatorService;

import org.apache.log4j.Logger;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;

public class RoomLocatorImpl extends BaseServiceImpl implements
		RoomLocatorService {
	static {
		logger = Logger.getLogger(RoomLocatorImpl.class);
	}

	private Dao<Room, Integer> roomDao;

	public RoomLocatorImpl() {
		try {
			roomDao = DaoManager.createDao(
					OrmLiteManager.getConnectionSource(), Room.class);
		} catch (SQLException e) {
			err("Failure to create Room Dao.", e);
		}
	}

	@Override
	public List<Room> findRoomIn(String location) {
		if (location == null) {
			return new LinkedList<>();
		}

		// construct a query using the QueryBuilder
		QueryBuilder<Room, Integer> statementBuilder = roomDao.queryBuilder();
		try {
			statementBuilder.where().eq(Room.LOCATION, location);
			List<Room> rooms = roomDao.query(statementBuilder.prepare());
			dbg("findRoomIn(" + location + "):rooms.size:" + rooms.size());
			return rooms;
		} catch (SQLException e) {
			err("Failure to read", e);
		}

		return new LinkedList<>();
	}

	@Override
	public List<String> getAllLocations() {
		List<Room> rooms = getAllRooms();
		if (rooms.size() < 1) {
			return new LinkedList<>();
		}
		HashSet<String> set = new HashSet<>();
		for (Room room : rooms) {
			set.add(room.getLocation());
		}
		List<String> locations = new LinkedList<>();
		for (Object object : set.toArray()) {
			String location = (String) object;
			locations.add(location);
		}
		dbg("getAllLocations:locations.size:" + locations.size());
		return locations;
	}

	@Override
	public List<Room> getAllRooms() {
		try {
			List<Room> rooms = roomDao.queryForAll();
			dbg("getAllRooms:rooms.size:" + rooms.size());
			return rooms;
		} catch (SQLException e) {
			err("Failure to read", e);
		}
		return new LinkedList<>();
	}

	@Override
	public Room add(Room room) {
		Room newRoom;
		try {
			newRoom = roomDao.createIfNotExists(room);
			dbg("added new Room:" + newRoom.toString());
			return newRoom;
		} catch (SQLException e) {
			err("Failure to read", e);
			return null;
		}
	}

	@Override
	public String delete(Room room) {
		DeleteBuilder<Room, Integer> delete = roomDao.deleteBuilder();
		try {
			delete.where().eq(Room.ROOMID, room.getRoomId());
			long cnt = roomDao.delete(delete.prepare());
			if(cnt>0){
				dbg("deleted old Room:" + room.toString());
				return "OK";
			}
			return "ERROR!!! Failure to remove room:"+room.toString();
		} catch (SQLException e) {			
			return err("Failure to delete"+ room.toString(), e);
		}
	}

}
